﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace TestAsyncClient_1
{
    /// <summary>
    ///  机器人
    /// </summary>
    public class Robot {

        public string name;
        public Socket socket;
        public const int BufferSize = 1024;
        public byte[] readBuffer = new byte[BufferSize];

        public Robot(string pname)
        {
            name = pname;
        }

        public void Connect(string host, int port)
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(host, port);

            // 
            Console.WriteLine($"[{name}]地址:{socket.LocalEndPoint.ToString()}");

            // Recv
            socket.BeginReceive(readBuffer, 0, BufferSize, SocketFlags.None, ReceiveCb, null);
        }

        private void ReceiveCb(IAsyncResult ar)
        {
            try
            {
                int count = socket.EndReceive(ar);

                // 数据处理
                string str = Encoding.UTF8.GetString(readBuffer, 0, count);
                Console.WriteLine($"[{name}] 收到:{str}");

                // 继续接收
                socket.BeginReceive(readBuffer, 0, BufferSize, SocketFlags.None, ReceiveCb, null);
            }catch(Exception e)
            {
                Console.WriteLine(e);
                Console.WriteLine("连接已断开");
                socket.Close();
            }
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        public void Send(string str) { 
            if(socket == null)
            {
                Console.WriteLine("socket is null! 请先进行连接.");
                return;
            }

            byte[] bytes = Encoding.UTF8.GetBytes(str);
            socket.Send(bytes);
        }

        /// <summary>
        /// 进行模拟
        /// </summary>
        //public void Simulation() {
        //    Thread t = new Thread(Loop);
        //    t.Start();
        //}

        //private void Loop()
        //{
        //    Console.WriteLine($"[{name}] 开始模拟");
        //}
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<Robot> lstRobot = new List<Robot>();
            for(int i = 0; i < 2; ++i)
            {
                lstRobot.Add(new Robot($"rb-{i}"));
            }

            foreach(Robot robot in lstRobot)
            {
                robot.Connect("127.0.0.1", 9999);
            }

            Random r = new Random();
            while(true && lstRobot.Count > 0)
            {
                // 随机挑一个
                int idx = r.Next() % lstRobot.Count;
                Robot robot = lstRobot[idx];
                string str = Console.ReadLine();
                switch (str)
                {
                    case "all_quit":
                        Console.WriteLine("全部退出!");
                        return;
                    default:
                        if(!string.IsNullOrEmpty(str))
                        {
                            Console.WriteLine($"[{robot.name}] send:{str}");
                            robot.Send(str);
                        }
                        break;
                }

                Thread.Sleep(1000);
            }
        }
    }
}
